var express = require('express');
var router = express.Router();

const bodyParser = require('body-parser');
const sha = require("./sha1");

/* GET users listing. */
router.post('/checkJWT', bodyParser.json(), (req, res) => {
    // 检查用户名是否为空
    if (!req.body["jwt"]
        || typeof req.body["jwt"] != "object") {
        res.json({
            err: 1,
            message: typeof req.body["jwt"]
        })
    } else {
        // 首先检查签名
        let token = req.body["jwt"];
        let headPart64 = token["headPart"];
        let payloadPart64 = token["payloadPart"];
        let originSignPartCode = token["signPart"];
        let nowSignPart = headPart64 + payloadPart64 + (Buffer.from("ServerSecret")).toString("base64")
        let nowSignPartCode = sha.b64_sha1(nowSignPart);
        // 签名合法性检查通过，检查有效期
        if (originSignPartCode == nowSignPartCode) {
            let headPart = JSON.parse(Buffer.from(headPart64, "base64").toString("utf-8"));
            let payloadPart = JSON.parse(Buffer.from(payloadPart64, "base64").toString("utf-8"));
            if ((new Date()).getTime() - payloadPart["exp"] > 0) {
                // Token已过期
                res.json({
                    status: 404,
                    headPart: headPart,
                    payloadPart: payloadPart,
                    outTime: (new Date()).getTime() - payloadPart["exp"]
                })
            } else {
                // 有效期检查通过，检查签发源和签发目标
                if (payloadPart["ori"] != 'a' || payloadPart["aim"] != 'b') {
                    res.json({
                        status: 403,
                        needOri: 'a',
                        getOri: payloadPart["ori"],
                        needAim: 'b',
                        getAim: payloadPart["aim"]
                    })
                } else {
                    // 所有检查通过
                    res.json({
                        status: 200,
                        headPart: headPart,
                        payloadPart: payloadPart,
                        lastTime: payloadPart["exp"] - (new Date()).getTime()
                    })
                }
            }
        } else {
            res.json({
                status: 304,
                originSignPartCode: originSignPartCode,
                nowSignPartCode: nowSignPartCode
            })
        }

    }
})

module.exports = router;